package com.zw.cloud.tools.controller.wechat;

import cn.hutool.json.XML;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zw.cloud.common.utils.DingTalkUtils;
import com.zw.cloud.common.utils.weixin.AesException;
import com.zw.cloud.common.utils.weixin.WeChatAesUtils;
import com.zw.cloud.tools.entity.wechat.WeChatReceiveMsg;
import com.zw.cloud.tools.entity.wechat.robot.ReceiveCallbackDTO;
import com.zw.cloud.tools.entity.wechat.robot.WeChatRobotReceiveMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * 微信机器人
 * https://chatbot.weixin.qq.com/
 * https://openai.weixin.qq.com/
 */
@RestController
@RequestMapping("/we-chat/robot")
@Slf4j
public class WeChatRobotController {

    @Autowired
    private RestTemplate restTemplate;

    public static final String robotToken = "B6NFmZ4QZywZm02raQ1hBG2v76hIfw";

    /**
     * 接收客服消息 回调接口
     * https://chatbot.weixin.qq.com/@arrangement0f6d6/platform/publishManage/applicationBinding?active=api
     * http://123.60.169.183/tool/we-chat/robot/receiveCallbackMsg
     * 配置后 公众号的消息会被接收
     */
    @PostMapping("/receiveCallbackMsg")
    public void receiveCallbackMsg(@RequestBody ReceiveCallbackDTO receiveCallbackDTO) throws AesException {
        String msg = WeChatAesUtils.decryptRobotMsg(receiveCallbackDTO.getEncrypted());
        cn.hutool.json.JSONObject receiveMsgMap = XML.toJSONObject(msg);
        WeChatRobotReceiveMsg receiveMsg = JSON.parseObject(String.valueOf(receiveMsgMap.get("xml")), WeChatRobotReceiveMsg.class);
        log.info("[WeChatRobotController][receiveCallbackMsg]receiveMsg is {}",receiveMsgMap.get("xml"));
        DingTalkUtils.sendDingTalkMsgWithSign("微信机器人","自动回答内容:\n" + receiveMsg.getContent().getMsg());
    }

    @PostMapping("/autoChat")
    public JSONObject autoChat(@RequestParam String query) {
        String signature = getSignature();
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("signature",signature);
        paramMap.put("query",query);
        return restTemplate.postForObject("https://chatbot.weixin.qq.com/openapi/aibot/" + robotToken, paramMap, JSONObject.class);
    }

    /**
     *  获取signature接口
     */
    private String getSignature() {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userid","zw");
        JSONObject result = restTemplate.postForObject("https://chatbot.weixin.qq.com/openapi/sign/" + robotToken, paramMap, JSONObject.class);
        return String.valueOf(result.get("signature"));
    }
}
